package com.well.register.util;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;

public class ThreadUtils {

    /* 默认线程池大小 */
    private static Integer DEFAULT_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    private static ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();

    private static ScheduledExecutorService scheduledExecutorService =
            new ScheduledThreadPoolExecutor(DEFAULT_THREAD_POOL_SIZE, new BasicThreadFactory.Builder()
                .namingPattern("Server-ThreadFactory-%d").build());

    /**
     * 获取多线程线程池
     * @return
     */
    public static ScheduledExecutorService scheduledThreadPool() {
        return scheduledExecutorService;
    }


    static {
        executor.setPoolSize(DEFAULT_THREAD_POOL_SIZE);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
    }

    /**
     * 获取支持Task类型线程池
     * @return
     */
    public static ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return executor;
    }

    /**
     * 执行定时任务
     * @param runnable runnable
     * @param trigger trigger
     * @return
     */
    public static ScheduledFuture<?> schedule(Runnable runnable, CronTrigger trigger) {
        return ThreadUtils.threadPoolTaskScheduler().schedule(runnable, trigger);
    }

    /**
     * @param runnable runnable
     */
    public static void execute(Runnable runnable) {
        Assert.notNull(runnable, "runnable is not null!");
        scheduledThreadPool().execute(runnable);
    }
}
